<template>
  <div>
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="800px" append-to-body @close="handleClose">
      <div class="search-container">
        <el-input v-model="searchKeyword" placeholder="请输入地址关键字" clearable @keyup.enter="handleSearch">
          <template #append>
            <el-button @click="handleSearch">
              <el-icon>
                <Search />
              </el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
      <div ref="mapContainer" class="map-container"></div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelection" :disabled="!selectedPoint">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, nextTick, onUnmounted } from 'vue';
import { debounce } from 'lodash-es';
import { Search } from '@element-plus/icons-vue';
import { ElMessage, ElLoading } from 'element-plus';
import { useAMap } from './useAMap';

const props = defineProps({
  dialogTitle: {
    type: String,
    default: '点击地图选点'
  },
  defaultPosition: {
    type: Object,
    default: () => null
  }
});

const emits = defineEmits(['confirm', 'cancel']);
const dialogVisible = ref(false);
const mapContainer = ref(null);
const searchKeyword = ref('');
let loadingInstance = null; // 定义加载实例

const {
  selectedPoint,
  openDialog: openMapDialog,
  destroyMap,
  handleSearch: mapHandleSearch,
  handleMapClick,
  clearMarker // 解构出清除标记的方法
} = useAMap(mapContainer, searchKeyword);

// 监听 selectedPoint 变化
watch(selectedPoint, (newPoint) => {
  if (newPoint?.name) {
    searchKeyword.value = newPoint.name;
  } else {
    searchKeyword.value = '';
  }
});

// 打开弹窗
const openDialog = async (position) => {
  dialogVisible.value = true;
  // 调用清除标记的方法
  clearMarker();
  await nextTick();
  try {
    await openMapDialog(position || props.defaultPosition);
  } finally {
    // 关闭加载状态
    // setTimeout(() => {
    //    loadingInstance.close();
    // },500)
  }
};

// 搜索处理（添加防抖）
const handleSearch = debounce(() => {
  mapHandleSearch(searchKeyword.value);
}, 300);

// 确认选择
const confirmSelection = () => {
  if (!selectedPoint.value) {
    ElMessage.warning('请先在地图上选择一个位置');
    return;
  }
  emits('confirm', selectedPoint.value);
  dialogVisible.value = false;
};

// 关闭弹窗
const handleClose = () => {
  emits('cancel');
};

// 组件卸载时清理资源
onUnmounted(() => {
  destroyMap();
  if (loadingInstance) {
    loadingInstance.close();
  }
});

defineExpose({
  openDialog
});
</script>

<style scoped>
/* 保持原有样式不变 */
.map-container {
  width: 100%;
  height: 500px;
  margin-top: 10px;
}

.search-container {
  margin-bottom: 10px;
}

.dialog-footer {
  text-align: right;
}
</style>